/*
路由&服务：
	后续考虑拆出来，不使用gin
*/
package router

import (
	cache "asy-cache/cache"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

var ca *cache.CacheNet

type String string

func (s String) Len() int {
	return len(s)
}

func InitRouter(ip, port string, node int, centerList []string, maxSpace int64) {
	lruCache := cache.NewLRUCache()
	if maxSpace > 0 {
		lruCache.SetSpace(maxSpace)
	}
	ca = cache.NewCacheNet(lruCache, ip+port, node, centerList)

	r := gin.Default()

	// 添加功能
	r.GET("/alive", Alive)
	r.POST("/get", Get)
	r.POST("/set", Set)
	r.POST("/del", Del)

	// 监听端口8000
	r.Run(port)
}

// 存活信息
func Alive(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{})
	return
}

// 获取键值对
func Get(c *gin.Context) {
	key := strings.Trim(c.PostForm("key"), " ")
	if key == "" {
		c.JSON(http.StatusNotAcceptable, gin.H{})
		return
	}
	get, ok := ca.Cache.Get(key)
	if ok {
		c.JSON(http.StatusOK, gin.H{
			"msg": get,
		})
	} else {
		c.JSON(http.StatusAccepted, gin.H{})
	}
}

// 设置键值对
func Set(c *gin.Context) {
	key := strings.Trim(c.PostForm("key"), " ")
	value := strings.Trim(c.PostForm("value"), " ")
	if key == "" || value == "" {
		c.JSON(http.StatusNotAcceptable, gin.H{})
		return
	}
	ca.Cache.Set(key, String(value))
	c.JSON(http.StatusOK, gin.H{
		"msg": "success",
	})
}

// 删除键值对
func Del(c *gin.Context) {
	key := strings.Trim(c.PostForm("key"), " ")
	if key == "" {
		c.JSON(http.StatusNotAcceptable, gin.H{})
		return
	}
	ok := ca.Cache.Del(key)
	if ok {
		c.JSON(http.StatusOK, gin.H{
			"msg": "success",
		})
	} else {
		c.JSON(http.StatusAccepted, gin.H{
			"msg": nil,
		})
	}
}
